import axios from 'axios'
import { ElMessage } from 'element-plus'
import {config} from "@/common/config";
async function request(route = "",params = {},method = "get"){
    let url = config.api_url+route
    let data = {success:null,err:null}
    let loginInfo = localStorage.getItem('login_info');
    let token = ""
    if(loginInfo != "" && loginInfo != null && loginInfo != 'undefined' ){
        loginInfo = JSON.parse(loginInfo)
        let c = new Date();
        let expires = loginInfo.expires
        if(expires - c.getTime() > 0){
            token = loginInfo.token
        }
        else{
            localStorage.removeItem('login_info');
        }
    }
    await axios({
        method:method,
        url:url,
        params:params,
        headers : {
            'token': token
        }
    }).then(function(res){
        if(res.data.code == 10009 || res.data.code == 10010){
            if(route == '/admin/admin/login'){
                data.success = res.data
            }
            else{
                localStorage.removeItem('login_info');
                localStorage.clear();
                window.location.href = "/"
            }
        }
        else{
            data.success = res.data
        }
    }).catch(function(err){
        data.err = err
    });
    return data
}
async function post(route = "",params = {},method = "post"){
    let result = null;
    let errorMessage = ""
    await request(route,params,method).then(reponse => {
        if(reponse.err != null){
            errorMessage = reponse.err.message
        }
        else if(reponse.success == "404 Not Found!"){
            errorMessage = reponse.success
        }
        else{
            let data = reponse.success
            if(data == null){
                errorMessage = "请求无数据"
            }
            else if(data.code != 10000){
                errorMessage = data.message
            }
            else{
                result = data
            }
        }
    }).catch(err=>{
        console.log(err)
        errorMessage = "请求数据异常"
    })
    if(errorMessage != ""){
        ElMessage({
            message: errorMessage,
            type: 'error',
            offset: window.screen.height / 2 - 90
        });
    }
    return result
}
async function del(route = "",params = {},method = "delete"){
    let result = null;
    let errorMessage = ""
    await request(route,params,method).then(reponse => {
        if(reponse.err != null){
            errorMessage = reponse.err.message
        }
        else if(reponse.success == "404 Not Found!"){
            errorMessage = reponse.success
        }
        else{
            let data = reponse.success
            if(data == null){
                errorMessage = "请求无数据"
            }
            else if(data.code != 10000){
                errorMessage = data.message
            }
            else{
                result = data
            }
        }
    }).catch(err=>{
        errorMessage = "请求数据异常"
    })
    if(errorMessage != ""){
        ElMessage({
            message: errorMessage,
            type: 'error',
            offset: window.screen.height / 2 - 90
        });
    }
    return result
}
async function put(route = "",params = {},method = "put"){
    let result = null;
    let errorMessage = ""
    await request(route,params,method).then(reponse => {
        if(reponse.err != null){
            errorMessage = reponse.err.message
        }
        else if(reponse.success == "404 Not Found!"){
            errorMessage = reponse.success
        }
        else{
            let data = reponse.success
            if(data == null){
                errorMessage = "请求无数据"
            }
            else if(data.code != 10000){
                errorMessage = data.message
            }
            else{
                result = data
            }
        }
    }).catch(err=>{
        errorMessage = "请求数据异常"
    })
    if(errorMessage != ""){
        ElMessage({
            message: errorMessage,
            type: 'error',
            offset: window.screen.height / 2 - 90
        });
    }
    return result
}
async function get(route = "",params = {},method = "get"){
    let result = null;
    let errorMessage = ""
    await request(route,params,method).then(reponse => {
        if(reponse.err != null){
            errorMessage = reponse.err.message
        }
        else if(reponse.success == "404 Not Found!"){
            errorMessage = reponse.success
        }
        else{
            let data = reponse.success
            if(data == null){
                errorMessage = "请求无数据"
            }
            else if(data.code != 10000){
                errorMessage = data.message
            }
            else{
                result = data
            }
        }
    }).catch(err=>{
        errorMessage = "请求数据异常"
    })
    if(errorMessage != ""){
        ElMessage({
            message: errorMessage,
            type: 'error',
            offset: window.screen.height / 2 - 90
        });
    }
    return result
}
async function upload(route = "",params = {}){
    let loginInfo = localStorage.getItem('login_info');
    let token = ""
    if(loginInfo != "" && loginInfo != null && loginInfo != 'undefined'){
        loginInfo = JSON.parse(loginInfo)
        let c = new Date();
        let expires = loginInfo.expires
        if(expires - c.getTime() > 0){
            token = loginInfo.token
        }
        else{
            localStorage.removeItem('login_info');
        }
    }
    let url = config.api_url+route
    let response = await axios.post(url, params, {
        headers: {
            'Content-Type': 'multipart/form-data',
            'token': token
        },
    });
    return response.data;
}
function downloadFile(route,params = {},ext = "") {
    let url =  config.api_url+route
    let loginInfo = localStorage.getItem('login_info');
    let token = ""
    if(loginInfo != "" && loginInfo != null && loginInfo != 'undefined' ){
        loginInfo = JSON.parse(loginInfo)
        let c = new Date();
        let expires = loginInfo.expires
        if(expires - c.getTime() > 0){
            token = loginInfo.token
        }
        else{
            localStorage.removeItem('login_info');
        }
    }
    axios({
        url,
        method: 'GET',
        responseType: 'blob',
        params:params,
        headers : {
            'token': token
        }
    }).then((response) =>{
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', Math.round(Math.random() * 99999)+'.'+ext);
        document.body.appendChild(link);
        link.click();
    });
}

export {
    request,
    post,
    del,
    put,
    get,
    downloadFile,
    upload

}
